<?php


namespace app\admin\controller\Admin;


use app\admin\controller\AppController;
use app\admin\model\Admin\AdminModel;
use app\admin\model\Admin\AdminRoleRelationModel;
use app\admin\model\Admin\MenuModel;
use app\Utils\ImageUtil;
use app\Utils\Util;
use Exception;
use think\facade\Db;
use think\Request;

class Admin extends AppController
{

    /**
     * 获取管理员信息
     * @param Request $request
     * @return array
     */
    public function getAdminInfo(Request $request)
    {
        //后面设置权限检查
        $admin = $this->admin;
        return Util::returnJson(self::CODE_DATA,$admin,"");
    }

    /**
     * 获取权限菜单
     * @param Request $request
     * @return array
     */
    public function getMenu(Request $request)
    {
        //后面设置权限检查
        $admin = $this->admin;
        $where = [['is_show','=',1]];
        if(!empty($admin['type'])){
            //普通管理员
            $roles = AdminRoleRelationModel::getAdminRoleRelationJoinWhere([['arr.admin_id','=',$admin['id']]]);
            $menus_ids = [];
            foreach ($roles as $role){
                $ids = explode(',',$role['menu_ids']);
                $menus_ids = array_merge($menus_ids,$ids);
            }
            $ids = implode(',',array_values(array_unique($menus_ids)));
            array_push($where,['id','in',$ids]);
            $menus = MenuModel::getMenuWhereMore($where);
        }else{
            //超级管理员
            $menus = MenuModel::getMenuWhereMore($where);
        }
        //赋值菜单
        $this->menus = $menus;
        $menus = Util::setMenuArray(0,$menus);
        return Util::returnJson(self::CODE_DATA,$menus,"");
    }

    /**
     * 分页查询
     * @param Request $request
     * @return array
     */
    public function getAdminList(Request $request)
    {
        $where = [
            ['type','=',1]
        ];
        $param = $request->param();
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        if(!empty($param['keyword'])){
            array_push($where,['account','like','%'.$param['keyword'].'%']);
        }
        if(!empty($is_show)){
            if($is_show == 1){
                array_push($where,['is_show','=',1]);
            }
            if($is_show == 2){
                array_push($where,['is_show','=',0]);
            }
        }

        $list = AdminModel::getAdminListWhere($page,$limit,$where);
        $count = AdminModel::getAdminCountWhere($where);
        foreach ($list as &$item){
            $item['head_img'] = ImageUtil::i()->replaceUrl($item['head_img']);
        }
        unset($item);

        return Util::returnPageJson(self::CODE_DATA,$count,$list,"");

    }

    /**
     * 添加
     * @param Request $request
     * @return array
     */
    public function addAdmin(Request $request)
    {
        $param = $request->param();
        $account    = !empty($param['account']) ? $param['account'] : "";
        $password   = !empty($param['password']) ? $param['password'] : "";
        $nick_name  = !empty($param['nick_name']) ? $param['nick_name'] : "";
        $mobile     = !empty($param['mobile']) ? $param['mobile'] : "";
        $email      = !empty($param['email']) ? $param['email'] : "";
        $is_show    = !empty($param['is_show']) ? $param['is_show'] : "";

        //图片上传
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "/admin/head_img/";
            $img = ImageUtil::i()->upload($file, $path);
        }

        $data = [
            'account'=>$account,
            'password'=>$password,
            'nick_name'=>$nick_name,
            'head_img'=>!empty($img) ? $img : "",
            'type'=>1,
            'mobile'=>$mobile,
            'email'=>$email,
            'up_time'=>date("Y-m-d H:i:s",time()),
            'add_time'=>date("Y-m-d H:i:s",time())
        ];

        if(!empty($is_show) && $is_show == "on"){
            $data['is_show'] = 1;
        }else{
            $data['is_show'] = 0;
        }

        Db::startTrans();
        try{
            $id = AdminModel::addAdmin($data);
            if ($id) {
                if(!empty($param['select'])){
                    $role_ids = explode(',',$param['select']);
                    $data = [];
                    foreach ($role_ids as $role_id){
                        $arr['admin_id'] = $id;
                        $arr['role_id'] = $role_id;
                        array_push($data,$arr);
                    }
                    $flag = AdminRoleRelationModel::addAdminRoleRelation($data);
                    if($flag){
                        DB::commit();
                        return Util::returnJson(self::CODE_SUCCESS, null, "添加成功");
                    }else{
                        DB::rollBack();
                        return Util::returnJson(self::CODE_ERROR, null, "添加失败3");
                    }
                }else{
                    DB::commit();
                    return Util::returnJson(self::CODE_SUCCESS, $id, "添加成功");
                }
            } else {
                DB::rollBack();
                return Util::returnJson(self::CODE_ERROR, null, "添加失败2");
            }
        }catch (Exception $e){
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "添加失败1");
        }
    }

    /**
     * 更新
     * @param Request $request
     * @return array
     */
    public function editAdmin(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        $password = !empty($param['password']) ? $param['password'] : "";
        $nick_name = !empty($param['nick_name']) ? $param['nick_name'] : "";
        $mobile = !empty($param['mobile']) ? $param['mobile'] : "";
        $email = !empty($param['email']) ? $param['email'] : "";
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        if(empty($id)){
            return Util::returnJson(self::CODE_ERROR,null,"参数错误");
        }

        $save = [
            'nick_name'=>$nick_name,
            'head_img'=>!empty($img) ? $img : "",
            'mobile'=>$mobile,
            'email'=>$email,
            'up_time'=>date("Y-m-d H:i:s",time())
        ];

        if(!empty($password)){
            $save['password'] = md5($password);
        }

        //图片上传
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "/admin/head_img/";
            $img = ImageUtil::i()->upload($file, $path);
            $save['head_img'] = $img;
        }

        if(!empty($is_show)){
            if($is_show == "on"){
                $save['is_show'] = 1;
            }else{
                $save['is_show'] = 0;
            }
        }else{
            $save['is_show'] = 0;
        }

        DB::startTrans();
        try{
            AdminModel::updateAdminWhere([['id','=',$id]],$save);
            if(!empty($param['select'])){
                //清除
                AdminRoleRelationModel::delAdminRoleRelationWhere([['admin_id','=',$param['id']]]);
                $role_ids = explode(',',$param['select']);
                $data = [];
                foreach ($role_ids as $role_id){
                    $arr['admin_id'] = $param['id'];
                    $arr['role_id'] = $role_id;
                    array_push($data,$arr);
                }
                $flag = AdminRoleRelationModel::addAdminRoleRelation($data);
                if($flag){
                    DB::commit();
                    return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
                }else{
                    DB::rollBack();
                    return Util::returnJson(self::CODE_ERROR, null, "修改失败1");
                }
            }else{
                DB::commit();
                return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
            }
        }catch (Exception $e){
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "修改失败2");
        }
    }

    /**
     * 删除
     * @param Request $request
     * @return array
     */
    public function delAdmin(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        //开启事务
        Db::startTrans();
        try{
            //中间逻辑代码
            $flag = AdminModel::delAdminWhere([['id','=',$id]]);
            if($flag){
                //清除
                AdminRoleRelationModel::delAdminRoleRelationWhere([['admin_id','=',$id]]);
                //提交事务
                Db::commit();
                return Util::returnJson(self::CODE_SUCCESS,null,"删除成功");
            }else{
                Db::rollBack();
                return Util::returnJson(self::CODE_ERROR,null,"删除失败4");
            }
        }catch (\Exception $e) {
            //回滚事务
            Db::rollBack();
            return Util::returnJson(self::CODE_ERROR,$e,"删除失败1");
        }
    }


    /**
     * 更新
     * @param Request $request
     * @return array
     */
    public function editAdminInfo(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        $password = !empty($param['password']) ? $param['password'] : "";
        $nick_name = !empty($param['nick_name']) ? $param['nick_name'] : "";
        $mobile = !empty($param['mobile']) ? $param['mobile'] : "";
        $email = !empty($param['email']) ? $param['email'] : "";
        if(empty($id)){
            return Util::returnJson(self::CODE_ERROR,null,"参数错误");
        }

        $save = [
            'nick_name'=>$nick_name,
            'head_img'=>!empty($img) ? $img : "",
            'mobile'=>$mobile,
            'email'=>$email,
            'up_time'=>date("Y-m-d H:i:s",time())
        ];

        if(!empty($password)){
            $save['password'] = md5($password);
        }

        //图片上传
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "/admin/head_img/";
            $img = ImageUtil::i()->upload($file, $path);
            $save['head_img'] = $img;
        }

        DB::startTrans();
        try{
            AdminModel::updateAdminWhere([['id','=',$id]],$save);
            DB::commit();
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
        }catch (Exception $e){
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "修改失败2");
        }
    }

}
